package tcards.android;

import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class DateField extends RelativeLayout {
	private void init(AttributeSet attrs) {
		TypedArray tArray = getContext().obtainStyledAttributes(attrs, R.styleable.Field);
		
		String text = tArray.getString(R.styleable.Field_label);
        if (text != null) { 
        	getLabel().setText(text + ":");
        }
        
        int width = tArray.getInt(R.styleable.Field_inputSize, 350) / 2;		
        getDateInput().getLayoutParams().width = width;
        getTimeInput().getLayoutParams().width = width;
        
		tArray.recycle();
	}	
	
	public DateField(Context context) {
		this(context, null, 0);
	}

	public DateField(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public DateField(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		LayoutInflater li = LayoutInflater.from(context);
		addView(li.inflate(R.layout.date_field, this, false));
		if (attrs != null) {
			init(attrs);
		}
		getDateInput().setHorizontallyScrolling(true);
		getTimeInput().setHorizontallyScrolling(true);
	}

	public TextView getLabel() {
		return (TextView) findViewById(R.id.dateLabel);
	}
	
	public EditText getDateInput() {
		return (EditText) findViewById(R.id.dateInput);
	}
	
	public EditText getTimeInput() {
		return (EditText) findViewById(R.id.timeInput);
	}

	public Date getDateValue() {
		Format dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mma");
		String date = getDateInput().toString();
		String time = getTimeInput().toString();
		Date value = null;
		try {
			value = (Date) dateFormat.parseObject(date + ' ' + time);
		}
		catch (ParseException e) {
			e.printStackTrace();
		}
		return value;
	}

	public void setDateValue(Date dateValue) {
		if (dateValue == null) {
			dateValue = new Date();
		}
		
		Format dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		Format timeFormat = new SimpleDateFormat("hh:mma");
		getDateInput().setText(dateFormat.format(dateValue));
		getTimeInput().setText(timeFormat.format(dateValue));
	}
}